import React from 'react';
import { Button, Row, Col, message, Tooltip } from 'antd';
import UserList from './list';
import CommonListsIndex from '../../../components/CommonLists/index';
import FilterTool from '../../../components/FilterTool';
import UserAdd from './add';
import Modal from '../../../components/Modal/index';
import CopyField from './copyField';
import AuditStatus from '../../../components/AuditStatus';
import { IS_SYSTEM, AUDIT } from '../../../utils/constant';
import RelationComponent from '../../Strategy/Strategy/Component/relation';
import RelationStrategy from '../../Strategy/Strategy/relation';
import RelationIndicator from '../Indicator/relation';
import { connect } from 'react-redux';

function mapStateToProps(state) {
  return {
    field_classification: state.code.field_classification || [],
  };
}

@connect(mapStateToProps)
class FieldIndex extends CommonListsIndex {
  constructor(props) {
    super(props);
    this.api = 'field';
    this.addComponent = UserAdd;
    this.editComponent = UserAdd;
    this.listsComponent = UserList;
    this.queryParams = {};
    this.initQueryPanigation = {
      current_page: 1,
      page_size: 10,
    };
    this.state = {
      ...this.state,
      field_ids: [], // 已勾选的字段，复制要用
      applications: [],
    };
    if (this.app_id) {
      this.queryTableParams.app_id = this.app_id;
    }
    if (this.event_id) {
      this.queryTableParams.event_id = this.event_id;
    }
    if (this.is_system) {
      this.queryTableParams.is_system = this.is_system;
    }
    this.model_width = 600;
  }
  componentDidMount() {
    this.getAppCodeList();
    this.getProductCodeList();
  }

  //打开复制字段的弹窗
  openCopyField = () => {
    if (this.state.field_ids.length < 1) {
      message.warning('请至少勾选一个字段');
      return;
    }
    Modal.open({
      title: '复制字段',
      width: '400px',
      content: (
        <CopyField
          applications={this.state.applications.filter((item) => item.app_id !== -1)}
          field_ids={this.state.field_ids}
          closeModal={this.closeCopyModal}
        />
      ),
      isOkBtn: false,
      maskClosable: false,
      isCancelBtn: false,
    });
  };

  // 关闭复制字段弹窗
  closeCopyModal = () => {
    Modal.close();
    this.freshQueryList();
  };

  // 关联组件
  showRelationComponent = (record) => {
    Modal.open({
      title: <>关联组件<span style={{ fontSize: 10, color: 'grey', marginLeft: 4 }}>仅展示当前部门拥有权限数据</span></>,
      width: '1000px',
      content: (
        <RelationComponent
          record={record}
          param={
            record.is_system === IS_SYSTEM._TRUE
              ? { type: 'field', strategy_type: 1, field_id: record.field_id }
              : { type: 'field', strategy_type: 1, app_id: record.app_id, event_id: record.event_id, field_id: record.field_id }
          }
        />
      ),
      isOkBtn: true,
      maskClosable: false,
      isCancelBtn: true,
      ok: () => Modal.close(),
    });
  };

  // 关联策略
  showRelationStrategy = (record) => {
    Modal.open({
      title: <>关联策略<span style={{ fontSize: 10, color: 'grey', marginLeft: 4 }}>仅展示当前部门拥有权限数据</span></>,
      width: '1000px',
      content: (
        <RelationStrategy
          record={record}
          param={
            record.is_system === IS_SYSTEM._TRUE
              ? { type: 'field', strategy_type: 2, field_id: record.field_id }
              : { type: 'field', strategy_type: 2, app_id: record.app_id, event_id: record.event_id, field_id: record.field_id }
          }
        />
      ),
      isOkBtn: true,
      maskClosable: false,
      isCancelBtn: true,
      ok: () => Modal.close(),
    });
  };

  showRelationIndicator = record => {
    let param = record.is_system === IS_SYSTEM._TRUE ? {
      field_id: record.field_id
    } : {
      app_id: record.app_id,
      event_id: record.event_id,
      field_id: record.field_id
    }
    Modal.open({
      title: <>关联指标<span style={{ fontSize: 10, color: 'grey', marginLeft: 4 }}>仅展示当前部门拥有权限数据</span></>,
      width: '1000px',
      content: (
        <RelationIndicator record={record} param={param} />
      ),
      isOkBtn: true,
      maskClosable: false,
      isCancelBtn: true,
      ok: () => Modal.close()
    });
  }

  getColumns = () => {
    return [
      {
        title: '字段名',
        key: 'field_name',
        dataIndex: 'field_name',
        ellipsis: true,
        width: 100,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              <div className="overflowtext">
                <Button type='link' onClick={() => this.showDetail(record)}>
                  {text}
                </Button>
              </div>
            </Tooltip>
          );
        },
      },
      {
        title: (
          <>
            {this.getFilterTitle(
              '所属渠道',
              this.state.applications,
              'app_id',
              this.refreshTableFilterWithAppV2.bind(this, 'app_id'),
              ['app_id', 'app_name']
            )}
          </>
        ),
        key: 'app_name',
        dataIndex: 'app_name',
        ellipsis: true,
        width: 100,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: (
          <>
            {this.getFilterTitle(
              '关联产品',
              this.state.products,
              'product_id',
              this.refreshTableFilterWithAppV2.bind(this, 'product_id'),
              ['product_id', 'product_name']
            )}
          </>
        ),
        key: 'product_name',
        dataIndex: 'product_name',
        ellipsis: true,
        width: 100,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: (
          <>
            {this.getFilterTitle(
              '关联事件',
              this.state.events,
              'event_id',
              this.refreshTableFilterWithAppV2.bind(this, 'event_id'),
              ['event_id', 'event_name']
            )}
          </>
        ),
        key: 'event_name',
        dataIndex: 'event_name',
        ellipsis: true,
        width: 100,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: (
          <>
            {this.getFilterTitle(
              '字段类型',
              [
                {
                  key: -1,
                  value: '全部字段',
                },
                {
                  key: IS_SYSTEM._TRUE,
                  value: '系统字段',
                },
                {
                  key: IS_SYSTEM._FALSE,
                  value: '自定义字段',
                },
              ],
              'is_system',
              this.refreshTableFilter,
              ['key', 'value']
            )}
          </>
        ),
        key: 'is_system',
        dataIndex: 'is_system',
        ellipsis: true,
        width: 100,
        render: (text, record) => {
          return (
            <>
              {record.is_system === IS_SYSTEM._TRUE && <span>系统字段</span>}
              {record.is_system === IS_SYSTEM._FALSE && <span>自定义字段</span>}
            </>
          );
        },
      },
      {
        title: '字段Code',
        key: 'field_code',
        dataIndex: 'field_code',
        ellipsis: true,

        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              <div className='overflowtext' style={{ width: '100%' }}>
                {text}
              </div>
            </Tooltip>
          );
        },
      },
      {
        title: (
          <>
            {this.getFilterTitle(
              '字段分类',
              this.props.field_classification,
              'classification',
              this.refreshTableFilter,
              ['code', 'value']
            )}
          </>
        ),
        key: 'classification_name',
        dataIndex: 'classification_name',
        ellipsis: true,
        width: 100,
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
      },
      {
        title: '数据类型',
        key: 'data_type',
        dataIndex: 'data_type',
        ellipsis: true,
      },
      {
        title: '关联指标',
        key: 'feature_count',
        dataIndex: 'feature_count',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Button
              type='link'
              onClick={this.showRelationIndicator.bind(this, record)}
            >
              {text}
            </Button>
          );
        },
      },
      {
        title: '关联组件',
        key: 'component_count',
        dataIndex: 'component_count',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Button
              type='link'
              onClick={() => {
                this.showRelationComponent(record);
              }}
            >
              {text}
            </Button>
          );
        },
      },
      {
        title: '关联策略',
        key: 'strategy_count',
        dataIndex: 'strategy_count',
        ellipsis: true,
        render: (text, record) => {
          return (
            <Button
              type='link'
              onClick={() => {
                this.showRelationStrategy(record);
              }}
            >
              {text}
            </Button>
          );
        },
      },
      {
        title: '创建/修改人',
        dataIndex: 'create_user_name',
        key: 'create_user_name',
        ellipsis: true,
        render: (text, record) => {
          var content = !!record.update_user_name
            ? `${record.create_user_name}/${record.update_user_name}`
            : `${record.create_user_name}/${record.create_user_name}`;
          return (
            <Tooltip title={content} placement='topLeft'>
              <div className='overflowtext' style={{ width: '100%' }}>
                {content}
              </div>
            </Tooltip>
          );
        },
      },
      {
        title: '修改时间',
        dataIndex: 'update_time',
        key: 'update_time',
        ellipsis: true,
        render: (text, record) => {
          var content = !!record.update_time ? record.update_time : record.create_time;
          return (
            <Tooltip title={content} placement='topLeft'>
              <div className='overflowtext' style={{ width: '100%' }}>
                {content}
              </div>
            </Tooltip>
          );
        },
      },
      {
        title: '审核情况',
        key: 'status',
        dataIndex: 'audit_label',
        render: (text, record) => {
          return <AuditStatus text={text} record={record} />;
        },
      },
    ];
  };

  clearSelected = () => {
    this.setState({
      field_ids: [],
    });
  };

  render() {
    const ListsComponent = this.listsComponent;
    // 字段选择配置
    const rowSelection = {
      columnWidth: 30,
      onChange: (selectedRowKeys, selectedRows) => {
        let field_ids = [];
        selectedRows.forEach((item) => {
          if (
            item.is_system !== IS_SYSTEM._TRUE &&
            (!Object.keys(item).includes('audit_status') || item.audit_status !== AUDIT._WAIT)
          ) {
            field_ids.push(item.field_id);
          }
        });
        this.setState({
          field_ids,
        });
      },
      getCheckboxProps: (record) => ({
        disabled:
          record.is_system === IS_SYSTEM._TRUE ||
          (Object.keys(record).includes('audit_status') && record.audit_status === AUDIT._WAIT),
      }),
      hideDefaultSelections: true,
      selectedRowKeys: this.state.field_ids,
    };
    const data = [
      {
        type: 'Search',
        key: 'keyword',
        name: 'keyword',
        defaultValue: '',
        placeholder: '请输入字段名|字段Code进行搜索',
      },
    ];
    return (
      <div>
        <Row type='flex' justify='space-between' align='middle'>
          <Col span={6}>
            <Button type='primary' onClick={this.add.bind(this, { title: '添加字段' })}>
              添加字段
            </Button>
            <Button className='marl10' onClick={this.openCopyField}>
              复制字段
            </Button>
          </Col>
          <Col span={18}>
            <FilterTool
              ref='filterTool'
              data={data}
              colNum={1}
              query={this.freshQueryList}
              refreshFilter={this.refreshFilter}
              isOnChange={true}
              justify='end'
              refresh={this.resetList}
            />
          </Col>
        </Row>
        <div className='inner-content' style={{ marginTop: '10px' }}>
          <ListsComponent
            {...this.state}
            rowKey='field_id'
            edit={this.edit}
            queryList={this.freshQueryList}
            clearSelected={this.clearSelected}
            columns={this.getColumns()}
            onChangePagination={this.onChangePagination}
            rowSelection={rowSelection}
          />
        </div>
      </div>
    );
  }
}

export default FieldIndex;
